import axios from 'axios'
// import store from '../../store/index'
import router from '../../router/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 观察者
let isRefreshing = true
let subscribers = []
function onAccessTokenFetched () {
  console.log(subscribers)
  subscribers.forEach((callback) => {
    callback()
  })
  subscribers = []
}

function addSubscriber (callback) {
  subscribers.push(callback)
}

// 创建axios实例
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const request = axios.create({
  baseURL: '/api'
})
request.interceptors.request.use(config => {
  NProgress.start()
  const token = localStorage.getItem('accessToken')
  if (token) {
    config.headers.token = token
  }
  return config
},
error => {
  return Promise.reject(error)
})

request.interceptors.response.use(async response => {
  NProgress.done()
  console.log(response.data)
  const status = response.data.state
  if (status == '401') {
    let refreshToken = localStorage.getItem('refreshToken')
    if (refreshToken) {
      if(isRefreshing){
        isRefreshing = false
        const res =  await axios.post('/api/refreshToken', refreshToken)
        if(!res) return ;
        if(res.data.state == '200'){
          const accessToken = res.data.data.accessToken
          const refreshToken = res.data.data.refreshToken
          localStorage.setItem('accessToken', accessToken)
          localStorage.setItem('refreshToken', refreshToken)
        } else if(res.data.state == '402'){
          localStorage.clear();
          await router.push('/')
        }
      }
      response.config.headers = {
        token: localStorage.getItem('accessToken'),
        'Content-Type': 'application/json;charset=utf-8'
      }
      subscribers = []
      // eslint-disable-next-line no-case-declarations
      const retryOriginalRequest = new Promise((resolve) => {
        addSubscriber(() => {
          resolve(request(response.config))
        })
      })
      onAccessTokenFetched()
      // 纸条撕掉
      // eslint-disable-next-line no-const-assign
      isRefreshing = true
      return retryOriginalRequest
    }
  } else if(status == '402'){
    //refreshToken 过期
    localStorage.clear();
    await router.push('/')
  } else {
    return response.data
  }
}, async error => {
  console.log(error)
  return Promise.reject(error)
})

request.defaults.retry = 3
request.defaults.retryDelay = 1000
request.defaults.timeout = 100000

export default request
